#include "passworddialog.h"
#include <QRegExpValidator>
#include <QAction>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QApplication>
#include <QStyle>
#include <QDebug>
#include <QMessageBox>
#include "dataprovider.h"

QLineEdit* PasswordDialog::createPasswordEdit(QString text) {
    // qDebug() << "PasswordDialog create Edit." << text;
    QLineEdit *edit = new QLineEdit(this);

    edit->setPlaceholderText(text);

    edit->setEchoMode(QLineEdit::Password);

    QAction *action = new QAction(edit);

    action->setIcon(QIcon(":/icons/icon/eye-closed.png"));

    // newPasswordAction->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogResetButton));
    action->setCheckable(true);

    edit->addAction(action, QLineEdit::TrailingPosition);

    edit->setTextMargins(0, 0, 30, 0);

    connect(action, &QAction::triggered, this, [=](bool checked){
        qDebug() << "Action Pressed: " << checked;
        QLineEdit::EchoMode mode = checked ? QLineEdit::Normal : QLineEdit::Password;
        edit->setEchoMode(mode);
        action->setIcon(checked ? QIcon(":/icons/icon/eye_open.png") : QIcon(":/icons/icon/eye-closed.png"));
    });
    // qDebug() << "PasswordDialog create Edit ok." << text;
    return edit;
}

// 初始化控件和布局
PasswordDialog::PasswordDialog(QWidget *parent) : QDialog(parent) {
    setWindowTitle("好用得效期系统");

    titleLabel = new QLabel("修改密码");
    // 创建输入框并设置属性
    oldPasswordEdit = createPasswordEdit("旧密码");
    oldPasswordEdit->setFocus();
    oldPasswordEdit->installEventFilter(this);
    newPasswordEdit = createPasswordEdit("新密码");
    newPasswordEdit->installEventFilter(this);

    // 设置输入验证规则
    QRegExp regExp("[0-9]{3,20}");
    QValidator *validator = new QRegExpValidator(regExp, this);
    newPasswordEdit->setValidator(validator);
    // connect(validator, &QValidator::changed, this, &PasswordDialog::validateInputs);
    connect(newPasswordEdit, &QLineEdit::textChanged, this, &PasswordDialog::validateInputs);

    confirmButton = new QPushButton("确认");
    confirmButton->setEnabled(false);
    cancelButton = new QPushButton("取消");
    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addWidget(confirmButton);
    buttonLayout->addWidget(cancelButton);

    keyboard = new DigitalKeyboard;

    // 布局管理
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(titleLabel);
    mainLayout->addWidget(oldPasswordEdit);
    mainLayout->addWidget(newPasswordEdit);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addWidget(keyboard);
    mainLayout->setAlignment(keyboard, Qt::AlignCenter);
    setLayout(mainLayout);

    applyStyles();

    qDebug() << "Create Password Dialog ok....";

    connect(confirmButton, &QPushButton::clicked, this, &PasswordDialog::onConfirm);
    connect(cancelButton, &QPushButton::clicked, this, &PasswordDialog::exitApplication);

    keyboard->attachTo(oldPasswordEdit);
}

void PasswordDialog::applyStyles(){
    setStyleSheet(R"(
        QDialog { background: #f0f2f5; }
        QLabel { font: 14px; color: #333; }
        QLineEdit {
            padding:8px;
            border:1px solid #ddd;
            border-radius:4px;
            font: 14px;
        }
        QPushButton {
          padding:10px 20px;
          border:2px solid #ddd;
          border-radius:4px;
          font:bold 14px;
        }
        QPushButton[text="登录"] { background:#4890ee; color:white; height: 40px; font: 24px bold;}
        QPushButton[text="登录"]:hover { background:#40a9ff; }
        QPushButton[text="退出"] { background:#ff6666; color:white; height: 40px; font: 24px bold;}
        )"
                  );

    titleLabel->setStyleSheet("font: bold 28px; color: #1a73e8;");
    titleLabel->setAlignment(Qt::AlignCenter);
}


// 输入验证逻辑
void PasswordDialog::validateInputs() {
    bool isValid = (newPasswordEdit->hasAcceptableInput());

    qDebug() << "validate changed: " << isValid;
    // 动态更新确认按钮状态
    QString oldPassword = oldPasswordEdit->text();
    QString newPassword = newPasswordEdit->text();
    if (!oldPassword.isEmpty() && !newPassword.isEmpty() && oldPassword != newPassword) {
        confirmButton->setEnabled(isValid);
    }
}

void PasswordDialog::onConfirm(){
    QString oldPassword = oldPasswordEdit->text();
    QString newPassword = newPasswordEdit->text();
    if (!oldPassword.isEmpty() && !newPassword.isEmpty() && oldPassword != newPassword) {
        auto dataProvider = DataProvider::instance();
        dataProvider->ChangePassword(oldPassword, newPassword);
        accept();
    } else {
        QMessageBox::warning(this, "密码修改错误", "设置密码不正确", QMessageBox::Ok);
    }
}

void PasswordDialog::exitApplication() {
    disconnect();
    close();
}

bool PasswordDialog::eventFilter(QObject *watched, QEvent *event) {
    if (event->type() == QEvent::FocusIn) {
        qDebug() << "Focus received by:" << watched->objectName();
        if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(watched)) {
            keyboard->attachTo(lineEdit);
        }
    }
    return QWidget::eventFilter(watched, event);
}
